<?php

require_once("../../classes/db_functions.php");
require_once("../../classes/functions.php");

$db = new db_functions();
$action = getFromInput("a");

if(!isUserLoggedIn()){
	switch ($action){
		case "login":
			loginUser();
			break;
		default:
			displayLoginform();
			break;
	}
	die();
}

switch ($action){
	case "search":
		searchDels();
		break;
	case "exec":
		doTheJob();
		break;
	case "logout":
		logoutUser();
		break;
	default:
		displaySearchForm();
		break;
}
function doTheJob(){
	global $db;
	
	$tables = array(
		"komitenti_delatnosti"	=> "komdel_del_id",
		"komitenti_brands"		=> "del_id",
		"komitenti_emails"		=> "del_id",
		"komitenti_webs"		=> "del_id",
		"komitenti_kwords"		=> "del_id",
		"komitenti_telefoni"	=> "del_id",
		"profili"				=> "profil_del_id",
		"preporuke"				=> "del_id"
	);
	
	$from = explode(",",getFromInput("from"));
	$to = getFromInput("to");
	
	$root = $_SERVER['DOCUMENT_ROOT'];
	$script = $_SERVER['SCRIPT_NAME'];
	$dir = substr($script,0,strrpos($script,"/"));
	//$backup_filename = "backup/".$_COOKIE["pdu"]."_".implode("-",array_slice($from,0,10))."_".$to;
	$backup_filename = "$root$dir/backup/".$_COOKIE["pdu"]."_".date("dmY_His");
	
	$_queries=array();
	foreach ($tables as $table_name=>$del_attr){
		$q = "SELECT * INTO OUTFILE '".$backup_filename."_".$table_name."' FROM $table_name WHERE ";
		foreach ($from as $delid){
			$q .= "$del_attr=$delid OR ";
		}
		$q = substr($q,0,strlen($q)-4);
		
		if(!$db->alterTable($q)){
			die("Error creating backup!\r\n".mysql_error());
		}
		
		$q = "UPDATE $table_name SET $del_attr=$to WHERE ";
		$ima=false;
		foreach ($from as $del){
			if($del != $to){
				$ima=true;
				$q .= 		"$del_attr=$del OR ";
			}
		}
		$_queries[count($_queries)] = substr($q,0,strlen($q)-4);
	}
	
	if($ima){
		$msg="Prebacivanje izvršeno";
		foreach ($_queries as $q){
			if(!$db->alterTable($q)){
				$msg = "Prebacivanje nije izvršeno!\n\nError:\n".mysql_error();
				break;
			}
		}
		echo $msg;
	}else{
		echo "Nema sta da se izmeni.";
	}
}

function displaySearchForm(){
	?>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" type="text/css" href="style.css" />
	<script type="text/javascript" language="javascript" src="http://cvet.yellow/yap1/js/main.js"></script>
	<script type="text/javascript" language="javascript" src="script.js"></script>
	<body>
	<div id="throbber">Please wait...</div>
	<div style="float:right"><a href="?a=logout">odjava</a></div>
	<form method="POST" action="javascript:void(0)" onSubmit="var kword=trim(this.elements['keyword'].value); if(kword.length){LoadRSDoc('?a=search&keyword='+kword,'updateSearchList')}">
		Naziv: <input type="text" name="keyword" value="<?php echo getFromInput("keyword") ?>" />
		<input type="hidden" name="a" value="search" />
		<input type="submit" value="traži..." />
	</form>
	<br clear="all" />
	
	<div class="holder">
		<h2>Rezultat pretrage:</h2>
		<div class="sel">
		<a href="javascript:void(0)" onClick="selectAll('searchList',1)">markiraj</a>
		<a href="javascript:void(0)" onClick="selectAll('searchList',0)">demarkiraj</a>
		</div><br clear="all" />
		<ol onMouseDown="return false;" onMouseUp="return true;" id="searchList"></ol><br clear="all" />
		<div class="info" id="status"></div>
		<div id="searchInfo" class="info">0 / 0</div>
	</div>
	<div style="float:left; margin:200px 10px 0px 10px;">
		<input type="button" value=">>" onClick="ubaci()" /><br clear="all" />
		<input type="button" value="<<" onClick="izbaci()" /><br clear="all" />
	</div>
	<div class="holder">
		<h2>Odabrane delatnosti:</h2>
		<div class="sel">
			<a href="javascript:void(0)" onClick="selectAll('moveBuffer',1)">markiraj</a>
			<a href="javascript:void(0)" onClick="selectAll('moveBuffer',0)">demarkiraj</a>
		</div><br clear="all" />
		<ol onMouseDown="return false;" onMouseUp="return true;" id="moveBuffer"></ol><br clear="all" />
		<div class="info"></div>
		<div id="searchInfo1" class="info">0 / 0</div>
	</div>
	<div class="holder" style="margin-left:10px;">
		<?php $dels = getDelatnosti(); ?>
		<h2>Prebaci u:</h2>
		<select name="uDelatnost" id="uDelatnost">
		<?php
			foreach ($dels as $k=>$del){
				echo '<option value="'.$del["delatnost_id"].'">'.$del["delatnost_ime"].' - ['.$del["delatnost_id"].']</option>';
			}
		?>
		</select>
		<input type="button" value="prebaci..." onClick="Execute()" style="float:right;" />
	</div>
	</body>
	<?php
}

function searchDels(){
	global $db;
	$keyword = getFromInput("keyword");
	
	$q = "SELECT DISTINCT delatnost_id, delatnost_ime FROM delatnosti WHERE delatnost_ime LIKE '%$keyword%' ORDER BY delatnost_id";
	$res = $db->select2($q);
	
	if($res !== false){
		foreach ($res as $k=>$row){
			echo "<li onmousedown=\"return false;\" onmouseup=\"return true;\" value=\"".$row["delatnost_id"]."\" onclick=\"select(this)\">".$row["delatnost_ime"]."</li>";
		}
	}else{
		echo "Nema delatnosti za zadati kriterijum.";
	}
}

function getDelatnosti(){
	global $db;
	$ret = $db->select2("SELECT delatnost_id, delatnost_ime FROM delatnosti ORDER BY delatnost_ime");
	return $ret;
}


/************************************************/
/*				USER LOGIN						*/
/************************************************/
function isuserLoggedIn(){
	if(isset($_COOKIE["pdu"]) && $_COOKIE["pdu"]>0){
		return true;
	}else{
		return false;
	}
}

function displayLoginForm(){
	?>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" type="text/css" href="style.css" />
	<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="loginForm">
		<input type="hidden" name="a" value="login" />
		<label for="user">Korisničko ime:</label><input type="text" name="user" id="user" /><br clear="all" />
		<label for="pass">Lozinka:</label><input type="password" name="pass" id="pass" />
		<?php
		$e = getFromInput("e");
		if($e){
			?>
			<div class="error" style="font-size:11px; margin:5px; float:left;">Prijava neuspela.</div>
			<?php
		}
		?>
		<input type="submit" value="prijava" />
	</form>
	<?php
}

function loginUser(){
	global $db;
	
	$user = getFromInput("user");
	$pass = getFromInput("pass");
	
	$q = "SELECT id FROM users WHERE username='$user' AND `password`=OLD_PASSWORD('$pass')";
	$uid = $db->getOne($q);
	
	$redirect = $_SERVER['PHP_SELF'];
	
	if($uid !== null){
		setcookie("pdu",$uid);
	}else{
		$redirect .= "?e=1";
	}
	header("Location: $redirect");
}

function logoutUser(){
	if(setcookie("pdu","")){
		header("Location: ".$_SERVER['PHP_SELF']);
	}else{
		echo "Error setting cookie";
	}
}
?>